package com.tywj.panda.customer.common.http

import com.tywj.lib.core.common.extension.applyScheduler
import com.tywj.lib.core.common.util.JsonUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.lifecycle.extension.attachToLifecycle
import com.tywj.lib.net.retrofit.request.BaseRequest
import io.reactivex.Observable
import org.json.JSONObject

/**
 * @desc 网络请求回调，返回数据为数组
 * @author June Yang
 * @date 2020/5/8
 */
abstract class PDArrayCallback<T>(
    private val clazz: Class<T>,
    isHandleErrorSelf: Boolean = true
) : PDBaseCallback(isHandleErrorSelf) {

    override fun onSuccess(data: String) {
        val responseData = JSONObject(data)
        val code = responseData.getInt("code")
        val message = responseData.getString("msg")

        if (code == 0) {
            val disposable = Observable.just(responseData)
                .map { it.getJSONArray("data").toString() }
                .map { JsonUtil.parseArray(it, clazz)!! }
                .applyScheduler()
                .subscribe(
                    {
                        success(it)
                    },
                    {
                        LogUtil.printStackTrace(it)
                        error(BaseRequest.ERROR_DATA, ERROR_DATA_DESC)
                    })
            request.lifecycleOwner?.let { disposable.attachToLifecycle(it) }
        } else {
            handleAsyncRequestError(code, message)
        }
    }

    abstract fun success(data: ArrayList<T>)
}